<template>
  <div class="page">
    <div class="title-wrap">
      <h3 class="sub-title success-color">
        3位数，分位数统计数字重复的情况
      </h3>
    </div>
    
    <div class="cont">
      <div class="input-wrap">
        <el-input
          v-model="inputValue"
          type="textarea"
          placeholder="请粘贴要统计的文本"
          :autosize="{ minRows: 6, maxRows: 20 }"
          @change="inputValueChange"
        />
      </div>
      <div class="tip">
        <span class="underline tap" @click="jumpToRule">使用规则</span>
      </div>
      <div class="split-char-wrap">
        <div class="label">单分隔符：</div>
        <div class="value" @touchmove.capture="stopPropagation" @mousewheel.capture="stopPropagation">
          <el-select
          v-model="splitChar"
          placeholder="请选择词与词的分隔符"
          clearable
        >
          <el-option
            v-for="item in splitCharOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        </div>
      </div>
      
      <!-- <div class="split-char-wrap">
        <div class="label">查0数据：</div>
        <div class="value">
          <el-input v-model="minNum" style="width: 100px" placeholder="最小值" />
          -
          <el-input v-model="maxNum" style="width: 100px" placeholder="最大值" @input="maxNumInput" />
        </div>
        
      </div> -->
      <div class="split-char-wrap">
        <div class="label">去掉括号内容：</div>
        <div class="value">
          <el-radio-group v-model="isRemoveBracket" @change="isRemoveBracketChange">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
          
        </div>
      </div>
      <div class="split-char-wrap">
        <div class="label">去掉中文：</div>
        <div class="value">
          <el-radio-group v-model="isRemoveZw" @change="isRemoveZwChange">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
          
        </div>
      </div>
      
      <div class="btn-group">
        <el-button type="primary" @click="startSplit">确定</el-button>
      </div>
      <!-- /[\s,，;；、.。；;\n\-_\t\\\/\?？\+]+/ -->
      
      <div class="result-wrap" v-if="groupResult">
        <div class="title">结果如下:
          <span class="link-btn" @click="downloadFile">下载txt结果</span>
          <span v-if="maxNum=='' || maxNum < 16380" class="link-btn" @click="downloadExcel">下载表格结果</span>
        </div>
        <!-- <div class="tools-wrap">
          <div class="label">排序方式：</div>
          <div class="value">
            <el-radio-group v-model="sortType" @change="sortResult">
              <el-radio :value="1">升序</el-radio>
              <el-radio :value="2">降序</el-radio>
            </el-radio-group>
          </div>
        </div> -->
        
       
        <div class="title">0-9统计结果如下：</div>
        <div class="result-list-wrap">
          <div class="result-item" v-for="(item,index) in zeroTo9GroupResult" :key="index">
            <div class="label">【{{item.num}}次】({{ item.valueList.length }}个)</div>:<div class="res-value">{{ item.valueStr }}</div>
          </div>
        </div>
        <div class="title">10-99统计结果如下：</div>
        <div class="result-list-wrap">
          <div class="result-item" v-for="(item,index) in tenTo99GroupResult" :key="index">
            <div class="label">【{{item.num}}次】({{ item.valueList.length }}个)</div>:<div class="res-value">{{ item.valueStr }}</div>
          </div>
        </div>
        <div class="title">其余统计结果如下：</div>
        <div class="result-list-wrap">
          <div class="result-item" v-for="(item,index) in groupResult" :key="index">
            <div class="label">【{{item.num}}次】({{ item.valueList.length }}个)</div>:<div class="res-value">{{ item.valueStr }}</div>
          </div>
        </div>
        <!-- <div class="title">详情如下:<span class="link-btn" @click="downloadFile">下载结果</span></div>
        <div class="result-list-wrap">
          <div class="result-item" v-for="(item,key) in result" :key="key">
            {{ key }}： <span class="res-value">{{ item }}（次）</span>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import {splitCharOptions} from '@/utils/constant'
import { ElMessage } from 'element-plus'
import { downFile,getShortTodayStr,numToString,keyNumObjToArray } from '../utils/tools'
import { isReqOverflow } from '../utils/userLimit'
import * as XLSX from 'xlsx-js-style';
import { adminDialog } from '@/components/adminDialog'
let path = '/countDuplicateWords/'
let storageIsRemoveBracketKey = path + 'isRemoveBracket'
let storageIsRemoveZwKey = path + 'isRemoveZw'
let storageIsRemoveBracket = localStorage.getItem(storageIsRemoveBracketKey)  || '1'
let storageIsRemoveZw = localStorage.getItem(storageIsRemoveZwKey) || '1'
// 最大数字位数
let maxNumLength = 0
export default {
  data() {
    return {
      sortType:2,
      splitCharOptions:splitCharOptions,
      inputValue: '',
      splitChar: '',
      tempGroupResult:null,
      groupResult:null, //归类总结后的结果
      minNum:'',
      maxNum:'',
      isRemoveBracket:storageIsRemoveBracket,
      isRemoveZw:storageIsRemoveZw,
      zeroTo9GroupResult:[],
      tenTo99GroupResult:[],
    }
  },

  methods: {
    convertItemToString(valueList){
      // console.log('convertItemToString valueList:',valueList)
      let hasComma = valueList.find(item => String(item).includes(','))
      if(hasComma){
        return valueList.join('、')
      }else {
        return valueList.join('，')
      }
    },

    stopPropagation(event){
      event.stopPropagation()
      event.preventDefault();
      return false
    },
    isRemoveBracketChange(value){
      // console.log('isRemoveBracketChange value:',value)
      localStorage.setItem(storageIsRemoveBracketKey,value)
    },
    isRemoveZwChange(value){
      // console.log('isRemoveZwChange value:',value)
      localStorage.setItem(storageIsRemoveZwKey,value)
    },
    maxNumInput(value){
      // console.log('maxNumInput value:',value)
      // let tempLen = String(value).length
      // if(tempLen > maxNumLength){
      //   maxNumLength = tempLen
      // }
      maxNumLength = String(value).length
    },
    inputValueChange(){
      if(this.maxNum){
        maxNumLength = String(this.maxNum).length
      }else {
        maxNumLength = 0
      }
    },
    startSplit(){
      // 超出免费限制
      if(isReqOverflow()){
        adminDialog.show()
        return 
      }
      
      if(!this.inputValue){
        ElMessage.error('请输入要统计的文本')
        return
      }
      if(this.minNum || this.maxNum){
        if(!/^\d+$/.test(this.minNum)){
          ElMessage.error('查0范围最小值必须是数字')
          return
        }
        if(!/^\d+$/.test(this.maxNum)){
          ElMessage.error('查0范围最大值必须是数字')
          return
        }
       
        if(this.minNum >= this.maxNum){
          ElMessage.error('最小值不能大于等于最大值')
          return
        }
        this.minNum = Number(this.minNum)
        this.maxNum = Number(this.maxNum)
      }
      let inputValue = this.inputValue.trim()
      
      

      let splitChar = this.splitChar
      let splitCharReg = null
      // console.log('splitChar:',splitChar)
      let resList = []
      // 如果分隔符不是换行符，就需要处理换行的情况
      if(splitChar !=='\\n'){
        let inputList = inputValue.split('\n')
        // 删除括号和网址
        inputList = inputList.map(item => {
          if(this.isRemoveBracket === '1'){
            item = item.replace(/\(.*?\)|\[.*?\]|\{.*?\}|\<.*?\>|【.*?】|⟮.*?⟯|⟨.*?⟩|《.*?》|/g, '')
          }
          // 删除网址
          item = item.replace(/(https?:\/\/[^\s]+)/g, '')
          // 删除网址
          item = item.replace(/(www\.[^\s]+)/g, '')
          // 删除邮箱
          return item
        })

        if(splitChar === ''){
          splitCharReg = /[\s,，、.。；;：:\n\-_\t\\\/\?？\+=!！\|]+/
        }else if(splitChar ==='无'){
          splitCharReg = ''
        }else {
          splitCharReg = new RegExp('['+splitChar+']+')
        }
        // console.log('splitCharReg:',splitCharReg)
        inputList.forEach(item => {
          if(item){
            let res = item.split(splitCharReg)
            resList = resList.concat(res)
          }
          
        })

      }else {
        splitCharReg = /\n/
        resList = inputValue.split(splitCharReg)
      }
      
      // console.log('splitCharReg:',splitCharReg)
      
      // console.log('resList:',resList)
      // 先排序，再统计各个词出现的次数
      
      

      // 过滤掉中文等内容,如果一个数中存在中文，则直接返回空
      resList  = resList.map(item=>{
        if(this.isRemoveZw === '1'){
          if(/[\u4e00-\u9fa5]/.test(item)){
            return ''
          }
        }
        return item
      })

      // 排除空格和空字符串
      resList = resList.filter(item => item.trim() !== '')
      // 获取最大数字

      // 对单组数字进行排序,每组数字都是从小到大排列
      // resList = resList.map(item=>{
      //   // 纯数字
      //   if(/^\d+$/.test(item)){
      //     return item.split('').sort((a,b) => a-b).join('')
      //   }
      //   return item
      // })
      
      
      // resList.forEach(item => {
      //   if(/^\d+$/.test(item)){
      //     if(String(item).length > maxNumLength){
      //       maxNumLength = String(item).length
      //     }
      //   }
      // })
      // console.log('maxNum:',maxNum)
     
      // 对数据进行格式化，如果小于10，则数字前补0
      // resList = resList.map(item =>{
      //   // 如果是数字
      //   if(/^\d+$/.test(item)){
      //     return numToString(Number(item), maxNumLength)
      //   }else{
      //     return item
      //   }
        
      // })
      // 统计0-9这10个数字出现的概率，比如123，124，则1出现2次，2出现2次，3出现1次 4 出现1次
      let zeroTo9Result = {}
      let resListString = resList.join('')
      let resListStringList = resListString.split('')
      for(let i=0;i<resListStringList.length;i++){
        let item = resListStringList[i]
        if(/^\d+$/.test(item)){
          if(zeroTo9Result[item]){
            zeroTo9Result[item]++
          }else {
            zeroTo9Result[item] = 1
          }
        }
      }
      // 补齐0-9，避免出现空的
      // for(let i=0;i<10;i++){
      //   if(!zeroTo9Result[i]){
      //     zeroTo9Result[i] = 0
      //   }
      // }
      // 
     
      this.zeroTo9GroupResult = keyNumObjToArray(zeroTo9Result)


      
      // 查找2位数出现的概率 比如123，124，则12出现2次，13出现1次，14出现1次，23出现1次，24出现1次
      /**
       * tenTo99Result
       * {
       *  11:2,
       *  12:1
       * }
       */
       let tenTo99Result = {}
      
      resList.forEach(item => {
        let itemList = item.split('')
        if(itemList.length === 3){
          let num1 = String(itemList[0]) + String(item[1])
          let num2 = String(itemList[0]) + String(item[2])
          let num3 = String(itemList[1]) + String(item[2])
          // console.log('num1 num2 num3:',num1,num2,num3)
          if(tenTo99Result[num1]){
            tenTo99Result[num1]++
          }else {
            tenTo99Result[num1] = 1
          }
          if(tenTo99Result[num2]){
            tenTo99Result[num2]++
          }else {
            tenTo99Result[num2] = 1
          }
          if(tenTo99Result[num3]){
            tenTo99Result[num3]++
          }else {
            tenTo99Result[num3] = 1
          }
        }
        
        
        
      })
      
      
      // console.log('tenTo99Result:',tenTo99Result)
      // let tempTenTo99Result = {}
      // for(let key in tenTo99Result){
      //   let num = tenTo99Result[key]
      //   if(tempTenTo99Result[num]){
      //     tempTenTo99Result[num].push(key)
      //   }else {
      //     tempTenTo99Result[num] = [key]
      //   }
      // }
      // console.log('tempTenTo99Result:',tempTenTo99Result)
      // let tenTo99GroupResult = []
      // // 对key进行排序，且是倒序
      // let tempTenTo99ResultKeys = Object.keys(tempTenTo99Result).sort((a,b) => b-a)
      // tempTenTo99ResultKeys.forEach(item=>{
      //   tenTo99GroupResult.push({
      //     num: item,
      //     valueList: tempTenTo99Result[item],
      //     valueStr: tempTenTo99Result[item].join(',')
      //   })
      // })
      this.tenTo99GroupResult = keyNumObjToArray(tenTo99Result)
      

      // 统计整个数字出现的次数 比如123，124， 123出现1次，124出现1次
      let resObj = {}
      resList.forEach(item => {
        if(resObj[item]){
          resObj[item]++
        }else {
          resObj[item] = 1
        }
      })
      // console.log('resList:',resList)
      // 出现0次的数据
      // let show0Nums = []
      // // 如果存在查0范围，则筛选出符合范围的
      // if(this.minNum!=='' || this.maxNum !== ''){
        
      //   for(let i= this.minNum;i<=this.maxNum;i++){
      //     let findIndex = resList.findIndex(item => Number(item) === i)
      //     // console.log('findIndex:',findIndex,i)
      //     if(findIndex === -1){
      //       show0Nums.push(numToString(i))
      //     }
      //   }
        
      // }
      // console.log('show0Nums:',show0Nums)
      
      // 归类后的结果
      let tempGroupResult = {}
      for(let key in resObj){
        let num = resObj[key]
        if(tempGroupResult[num]){
          tempGroupResult[num].push(key)
        }else {
          tempGroupResult[num] = [key]
        }
      }
      // 如果存在查0范围，则筛选出符合范围的
      // if(show0Nums.length > 0){
      //   tempGroupResult[0] = show0Nums
      // }
      // console.log('tempGroupResult:',tempGroupResult)
      this.tempGroupResult = tempGroupResult
      this.sortResult()
    },
    
    sortResult(){
      let tempGroupResult = this.tempGroupResult
      let groupResultKeys = Object.keys(tempGroupResult)
      groupResultKeys.sort((a,b) => {
        if(this.sortType ===2){
          return  b - a
        }else {
          return a - b
        }
      })
      for(let key in tempGroupResult){
        tempGroupResult[key].sort((a, b) => Number(a) - Number(b))
      }
      // console.log('groupResultKeys:',groupResultKeys)
      // let groupResultNew = {}
      let groupResult = []
      groupResultKeys.forEach(num => {
        groupResult.push({
          num,
          valueList:tempGroupResult[num],
          valueStr:this.convertItemToString(tempGroupResult[num])
        })
        // groupResultNew[key] = tempGroupResult[key]
      })

      this.groupResult = groupResult
      ElMessage({
        message: '处理成功',
        type: 'success',
      })
    },
    downloadFile(){
      // 超出免费限制
      // 超出免费限制
      if(isReqOverflow()){
        adminDialog.show()
        return 
      }
      let str = ''
      str+='0-9统计结果\r\n'
      for(let item of this.zeroTo9GroupResult){
        str += `【${item.num}次】（${item.valueList.length}个）：${item.valueStr}\r\n`
      }
      str+='\r\n10-99统计结果\r\n'
      for(let item of this.tenTo99GroupResult){
        str += `【${item.num}次】（${item.valueList.length}个）：${item.valueStr}\r\n`
      }
      str+='\r\n其余统计结果\r\n'
      for(let item of this.groupResult){
        str += `【${item.num}次】（${item.valueList.length}个）：${item.valueStr}\r\n`
      }
      let blob = new Blob([str], {type: "text/plain;charset=utf-8"});
      downFile('统计结果_'+getShortTodayStr()+'.txt',blob)
    },
    downloadExcel(){
      // 超出免费限制
      // 超出免费限制
      if(isReqOverflow()){
        adminDialog.show()
        return 
      }
      let wb = XLSX.utils.book_new()
      // groupResult [{num:1,valueStr:'1',valueList:['1']}]
      let groupResult = this.groupResult
      let colNum = 0
      // 0-9
      this.zeroTo9GroupResult.forEach(item => {
        if(item.valueList.length > colNum){
          colNum = item.valueList.length
        }
      })
      // 10-99
      this.tenTo99GroupResult.forEach(item => {
        if(item.valueList.length > colNum){
          colNum = item.valueList.length
        }
      })
      groupResult.forEach(item => {
        if(item.valueList.length > colNum){
          colNum = item.valueList.length
        }
      })
      // 
      
      let excelAoa = []
      let header = ['出现次数']
      for(let i = 1;i<=colNum;i++){
        header.push('号码'+i)
      }
      excelAoa.push(header)
      // 0-9
      excelAoa.push(['0-9统计结果'])
      this.zeroTo9GroupResult.forEach(item => {
        let row = [item.num]
        for(let i = 0;i<item.valueList.length;i++){
          row.push(item.valueList[i])
        }
        for(let i = item.valueList.length;i<colNum;i++){
          row.push('')
        }
        excelAoa.push(row)
      })
      // 10-99
      excelAoa.push(['10-99统计结果'])
      this.tenTo99GroupResult.forEach(item => {
        let row = [item.num]
        for(let i = 0;i<item.valueList.length;i++){
          row.push(item.valueList[i])
        }
        for(let i = item.valueList.length;i<colNum;i++){
          row.push('')
        }
        excelAoa.push(row)
      })
      // 100-999
      excelAoa.push(['其余统计结果'])
      groupResult.forEach(item => {
        let row = [item.num]
        for(let i = 0;i<item.valueList.length;i++){
          row.push(item.valueList[i])
        }
        for(let i = item.valueList.length;i<colNum;i++){
          row.push('')
        }
        excelAoa.push(row)
      })
      let excelWorkSheet = XLSX.utils.aoa_to_sheet(excelAoa)
      XLSX.utils.book_append_sheet(wb,excelWorkSheet,'统计结果')
      let abuffer = XLSX.write(wb,{bookType:'xlsx',type:'array'})
      let blob = new Blob([abuffer], {type:"application/octet-stream"});
      downFile('统计结果_'+getShortTodayStr()+'.xlsx',blob)
    },
    jumpToRule(){
      this.$router.push('/numRepeatRules')
    }
  }
}
</script>

<style lang="scss" scoped>
.tip{
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
  line-height: 20px;
  color: blue;
  .tap{
    cursor: pointer;
  }
  .underline{
    text-decoration: underline;
  }
  
}
.cont {
  margin: auto;
  // max-width: 600px;
  border-radius: 4px;
  padding: 20px;
  padding-bottom: 60px;
  box-sizing: border-box;
  background: rgba(17, 150, 219, 0.1);
  overflow-x: hidden;
  .input-wrap{

  }
  
  .split-char-wrap{
    display: flex;
    align-items: center;
    margin-top: 16px;
    justify-content: flex-end;
    .label{
      text-align: right;
      margin-right: 10px;
      // flex-shrink: 0;
      word-break: keep-all;
      
    }
    .value{
      width: 200px;
      min-width: 200px;
      flex-shrink: 0;
    }
    
  }
  
  .btn-group {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .result-wrap{
    // background-color: #f5f5f5;

    .title{
      margin-top: 32px;
      font-weight: bold;
      .link-btn{
        margin-left: 20px;
        text-decoration: underline;
        cursor: pointer;
        color:blue
        
      }
    }
    .tools-wrap{
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .result-list-wrap{
      margin-top: 20px;
      background-color: #f5f5f5;
      padding:20px 8px 40px;
      box-sizing: border-box;
      border-radius: 4px;
    }
    .result-item{
      word-break: break-all;
      margin-top: 20px;
      display: flex;
      align-items: flex-start;
      .label{
        flex-shrink: 0;
        width: 110px;
        word-break: keep-all;
      }
      .res-value{
        margin-left: 10px;
        color:red;
        word-break: break-word;
      }
    }
  }
}
</style>
